package com.iwdnb.gkgz.ui.controller;

import java.util.List;

import com.iwdnb.bmnf.common.model.result.Result;
import com.iwdnb.gkgz.application.service.StockPoolService;
import com.iwdnb.gkgz.common.model.dto.Stock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author pengl
 * @date 2020/11/9
 */
@RestController
@RequestMapping("/api/stock/pool")
public class StockPoolController {

    @Autowired
    StockPoolService stockPoolService;

    @Autowired
    TaskExecutor taskExecutor;

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Result<Stock> addStock(Stock stock){
        Stock addStock = stockPoolService.addStock(stock);

        refreshStockPoolList();
        return Result.getSuccessResult(addStock);
    }

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Result<List<Stock>> getStockList(){
        return Result.getSuccessResult(stockPoolService.getStockList());
    }


    @RequestMapping(value = "/{code}",method = RequestMethod.GET)
    public Result findByCode(@PathVariable String code){
        Stock stock = stockPoolService.findByCode(code);

        refreshStockPoolList();
        return Result.getSuccessResult(stock);
    }

    @RequestMapping(value = "/delete/{code}",method = RequestMethod.GET)
    public Result removeStock(@PathVariable String code){
        Stock stock = new Stock();
        stock.setCode(code);
        stockPoolService.removeStock(stock);

        refreshStockPoolList();
        return Result.getSuccessResult(null);
    }

    /**
     * 异步刷新股票池缓存
     */
    public void refreshStockPoolList(){
        taskExecutor.execute(()-> {
            stockPoolService.getStockList();
        });
    }
}
